package com.test.practice.io.otherstream;

import lombok.Cleanup;

import java.io.*;

/**
 * 1.标准输入输出流
 * 2.打印流
 * 3.数据流
 *
 * @Description: 标准输入输出流Demo
 * =======================
 * @Author: Jovi
 * =======================
 * @Date: Created in 2023-02-10
 * =======================
 * @Version: 1.1.2.0
 */
public class OtherStreamDemo {

    public static void main(String[] args) throws Exception {

//        m1();

//        m2();

        m3();
    }

    /**
     * 数据流 使用DataOutputStream写入数据类型的顺序与
     * DataInputStream读出数据类型的顺序要一致
     * @throws IOException
     */
    private static void m3() throws IOException {
        // 实例化FileOutputStream对象
        FileOutputStream fos = new FileOutputStream("ttt.txt");
        // 实例化BufferedOutputStream对象
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        // 实例化DataOutPutStream对象
        DataOutputStream dos = new DataOutputStream(bos);
        // 写操作
        dos.writeByte(1);
        dos.writeLong(22222);
        dos.writeChar('b');
        dos.writeUTF("hello");
        dos.close();
        bos.close();
        fos.close();
        System.out.println("===========完成文件写出，开始读取文件==========");
        //使用DataInputStream进行读操作
        //实例化FileInputStream对象
        FileInputStream fis = new FileInputStream("ttt.txt");
        //实例化BufferedInputStream对象
        BufferedInputStream bis = new BufferedInputStream(fis);
        //实例化DataInputStream对象
        DataInputStream dis = new DataInputStream(bis);
        //读操作


        System.out.println(dis.readByte());
        System.out.println(dis.readLong());
        System.out.println(dis.readChar());
        System.out.println(dis.readUTF());

        dis.close();
        bis.close();
        fis.close();
        System.out.println("==========读取完毕==========");
    }

    /**
     * 打印流
     *
     * @throws FileNotFoundException
     */
    private static void m2() throws FileNotFoundException {
        FileOutputStream fos = new FileOutputStream("/text.txt");
        // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
        PrintStream ps = new PrintStream(fos, true);
        // 把标准输出流(控制台输出)改成文件
        if (ps != null) {
            System.setOut(ps);
        }
        // 输出ASCII字符
        for (int i = 0; i <= 255; i++) {
            System.out.print((char) i);
            // 每50个数据一行
            if (i % 50 == 0) {
                // 换行
                System.out.println();
            }
        }
    }

    private static void m1() throws IOException {
        //字节转字符的转换流
        @Cleanup InputStreamReader isr = new InputStreamReader(System.in);
        //字符缓冲流缓冲流
        @Cleanup BufferedReader br = new BufferedReader(isr);

        System.out.println("请输入字符串：");
        for (; ; ) {
            String data = br.readLine();
            if (data.equals("e")) {
                break;
            }
            System.out.println(data.toUpperCase());
        }
    }
}
